package com.ebj.demo.netty.codec_thrift;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.apache.thrift.TBase;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TTransport;

/**
 * Created by xiangyongzhou on 2017/7/11.
 */
public class ThriftEncoder extends MessageToByteEncoder<TBase<?, ?>>
{

    private static final byte[] LENGTH_PLACEHOLDER = new byte[4];

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext,
            TBase<?, ?> msg, ByteBuf out)
            throws Exception
    {
        final TTransport transport = new TIOStreamTransport(new ByteBufOutputStream(out));
        final TProtocol protocol = new TCompactProtocol(transport);
//        final TProtocol protocol = new TBinaryProtocol(transport);
        msg.write(protocol);
        transport.flush();
    }
}
